﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Yipusoft.Account.BLL;
using Yipusoft.Account.Model;
using Yipusoft.Common.BLL;
using Yipusoft.Common.Model;
using Yipusoft.Task.BLL;
using Yipusoft.Task.Model;
using System.Collections.Generic;
using System.Text;

public partial class Task_NewTask : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, "100101"))
        {
            Response.Write("<script>alert('没有权限！');history.back(0);</script>");
        }
        string DepartmentId = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        if (DepartmentId.Substring(0, 4) != "1300" && DepartmentId.Substring(4, 1) == "0")
        {
            Response.Redirect("NewTaskDetachment.aspx");
        }
        else
        {
            if (DepartmentId.Substring(0, 6) == "130004")
            {
                cbHY.Visible = true;

            }
            else
            {
                cbHY.Visible = false;
            }
        }


        if (!IsPostBack)
        {



            BindTypeList();
            StartDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            EndDate.Text = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd");
            //StartDate.Attributes.Add("onchange", "CheckDate('" + StartDate.ClientID + "')");
            //EndDate.Attributes.Add("onchange", "EvalDate('" + StartDate.ClientID + "','" + EndDate.ClientID + "')");
            BindUserList();

            if (Request.QueryString["TaskId"] != null)
            {
                ActionTitle.Text = "编辑任务";
                BindData();
            }
            else
            {
                ActionTitle.Text = "下达任务";
            }
            SetCbNextMonthEnabled();

        }
    }
    private void BindTypeList()
    {
        List<TaskTypeInfo> types = TaskType.GetTaskTypes();
        foreach (TaskTypeInfo type in types)
        {
            ListItem li = new ListItem();
            li.Text = type.TypeName;
            li.Value = type.TypeId.ToString();
            TypeList.Items.Add(li);
        }
        TypeList.SelectedIndex = 0;
    }
    private void BindUserList()
    {
        List<DepartmentInfo> departments;
        //如果当前操作人员是总队人员
        //列出各支队对口部门列表
        string DepartmentId = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        departments = Department.GetList("SUBSTRING(DepartmentID,3,2)<>'00' AND SUBSTRING(DepartmentID,5,1)='0' AND SUBSTRING(DepartmentID,6,1)=SUBSTRING('" + DepartmentId + "',6,1) AND SUBSTRING(DepartmentID,7,1)='0'");
        foreach (DepartmentInfo department in departments)
        {
            ListItem li = new ListItem();
            li.Text = department.ShortName;
            li.Value = department.DepartmentID;
            li.Selected = true;
            UserList.Items.Add(li);
        }
    }
    private void BindData()
    {
        TaskInfo task = Task.GetTask(int.Parse(Request.QueryString["TaskId"]));
        TaskTitle.Text = task.Title;
        TypeList.SelectedIndex = TypeList.Items.IndexOf(TypeList.Items.FindByValue(task.TaskType.ToString()));
        TaskComment.Text = task.Comment;
        StartDate.Text = task.StartDate.ToString("yyyy-MM-dd");
        EndDate.Text = task.EndDate.ToString("yyyy-MM-dd");
        List<TaskUserInfo> users = task.Users;
        List<string> strUsers = new List<string>();
        foreach (TaskUserInfo user in users)
        {
            strUsers.Add(user.UserId);
        }
        int j = UserList.Items.Count;
        for (int i = 0; i < j; i++)
        {
            if (strUsers.Contains(UserList.Items[i].Value))
            {
                UserList.Items[i].Selected = true;
            }
            else
            {
                UserList.Items[i].Selected = false;
            }
        }
        txtLadePines.Text = task.LatePoints.ToString();
        cbNextMonth.Checked = task.IsNextMonth;
        if (task.Child > 0)
        {
            txtLadePines.Text = "0";
            txtLadePines.Enabled = false;
        }
    }
    private void Insert()
    {
        TaskInfo task = new TaskInfo();
        task.TaskType = int.Parse(TypeList.SelectedValue);
        task.ParentId = 0;
        task.Title = TaskTitle.Text;
        task.Comment = TaskComment.Text;
        task.StartDate = DateTime.Parse(StartDate.Text);
        task.EndDate = DateTime.Parse(EndDate.Text);
        task.CreateDepartment = Yipusoft.Account.BLL.User.GetUser(Context.User.Identity.Name).DepartmentID;
        task.CreateUser = Yipusoft.Account.BLL.User.GetUser(Context.User.Identity.Name).UserName;
        task.CreateDate = DateTime.Now;
        task.UpdateDepartment = Yipusoft.Account.BLL.User.GetUser(Context.User.Identity.Name).DepartmentID;
        task.UpdateUser = Yipusoft.Account.BLL.User.GetUser(Context.User.Identity.Name).UserName;
        task.UpdateDate = DateTime.Now;
        task.IsNextMonth = cbNextMonth.Checked;
        task.LatePoints = Convert.ToDecimal(txtLadePines.Text);
        task.Locked = false;
        int taskId = Task.Insert(task);
        InsertTaskUsers(taskId);

        EventLogInfo log = new EventLogInfo();
        log.EventTime = DateTime.Now;
        log.EventType = 1;
        log.EventData = "下达任务";
        log.ItemID = taskId.ToString();
        log.ItemName = "Tasks";
        log.ItemFullUrl = "NewTask.aspx";
        log.CreatedBy = Context.User.Identity.Name;
        log.CreatedTime = DateTime.Now;
        log.UserIP = Request.UserHostAddress;
        EventLog.Insert(log);

        if (taskId > 0)
            Response.Redirect("SaveTask.aspx?RootId=" + taskId.ToString() + "&TaskId=" + taskId.ToString());
    }
    private void Update()
    {
        TaskInfo task = Task.GetTask(int.Parse(Request.QueryString["TaskId"]));
        task.TaskType = int.Parse(TypeList.SelectedValue);
        task.Title = TaskTitle.Text;
        task.Comment = TaskComment.Text;
        task.StartDate = DateTime.Parse(StartDate.Text);
        task.EndDate = DateTime.Parse(EndDate.Text);
        task.UpdateDepartment = Yipusoft.Account.BLL.User.GetUser(Context.User.Identity.Name).DepartmentID;
        task.UpdateUser = Yipusoft.Account.BLL.User.GetUser(Context.User.Identity.Name).UserName;
        task.UpdateDate = DateTime.Now;
        task.IsNextMonth = cbNextMonth.Checked;
        task.LatePoints = Convert.ToDecimal(txtLadePines.Text);
        InsertTaskUsers(int.Parse(Request.QueryString["TaskId"]));

        EventLogInfo log = new EventLogInfo();
        log.EventTime = DateTime.Now;
        log.EventType = 1;
        log.EventData = "更新任务";
        log.ItemID = Request.QueryString["TaskId"];
        log.ItemName = "Tasks";
        log.ItemFullUrl = "NewTask.aspx";
        log.CreatedBy = Context.User.Identity.Name;
        log.CreatedTime = DateTime.Now;
        log.UserIP = Request.UserHostAddress;
        EventLog.Insert(log);

        if (Task.Update(task))
            Response.Redirect("SaveTask.aspx?RootId=" + Request.QueryString["TaskId"] + "&TaskId=" + Request.QueryString["TaskId"]);
    }
    protected void ButtonSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (Request.QueryString["TaskId"] == null)
            {
                Insert();
            }
            else
            {
                Update();
            }
        }
        catch (Exception ex)
        {
            Prompt.Text = "错误：" + ex.Message;
        }
    }
    private void InsertTaskUsers(int taskId)
    {
        foreach (ListItem li in UserList.Items)
        {
            if (li.Selected)
            {
                TaskUserInfo user = new TaskUserInfo(taskId, li.Value, 0, 0, false, false, "");
                TaskUser.Insert(user);
            }
            else
            {
                TaskUser.Delete(taskId, li.Value);
            }
        }
        string hydepartmentid = "1314100";
        if (cbHY.Checked)
        {
            TaskUserInfo user = new TaskUserInfo(taskId, hydepartmentid, 0, 0, false, false, "");
            TaskUser.Insert(user);
        }
        else
        {
            TaskUser.Delete(taskId, hydepartmentid);

        }
    }
    protected void ButtonCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("TaskList.aspx");
    }
    protected void StartDate_TextChanged(object sender, EventArgs e)
    {
        SetCbNextMonthEnabled();
    }

    private void SetCbNextMonthEnabled()
    {
        if (StartDate.Text == "" || EndDate.Text == "")
        {
        }
        else
        {
            DateTime sd = Convert.ToDateTime(StartDate.Text);
            DateTime ed = Convert.ToDateTime(EndDate.Text);
	  if(sd.Year==ed.Year)
	{
            if (sd.Month < ed.Month)
            {
                cbNextMonth.Enabled = true;
            }
            else
            {
                cbNextMonth.Checked = false;
                cbNextMonth.Enabled = false;
            }
	}
	else
	{
		cbNextMonth.Enabled = true;
	}
        }
    }
    protected void EndDate_TextChanged(object sender, EventArgs e)
    {
        SetCbNextMonthEnabled();
    }



}
